

import { app, dialog} from 'electron'
// 基础变量定义
const request  = require('request')
const { Notification  } = require('electron')
const path = require('path');
const fs = require('fs');
const baseUrl = path.join(path.dirname(app.getPath('exe')) ,'./resources');
const packageLocation =  `${baseUrl}/app/package.json`;
const fileUrl = "http://www.tt.com/win32/";//这里需要修改为自己的资源外网
var AdmZip = require('adm-zip');

// 进度条
const progress = require('progress-stream');
const url = `${fileUrl}app.zip?v=${new Date().getTime()}`;


// description

export async function updateVersion(event) {
    const localpackage = await getLocalPackage(packageLocation);
    
    update(localpackage)   
    

}
async function getLocalPackage(loc) {
  return new Promise(async (resolve,reject)=>{
    let existed = await isFileExisted(loc)
    let con = ''
    if (existed){
        con = fs.readFileSync(loc,'utf-8')
        resolve(con)
    }else{
       reject("err");
    }
  })

}
function isFileExisted(loc){
    return new Promise( (resolve, reject) => {
        fs.access(loc, (err) => {
          
            if (err) {
              reject(false);
            } else {
                resolve(true);
            }
            
        })
    })
}



function update(localpackage) {
    return new Promise((resolve, reject) => {
      request(
        {
          url: `${fileUrl}package.json?v=${new Date().getTime()}`,//请求package.json，与本地对比版本号
        },
        (error, res, body) => {
          console.log(body)
          try {
            if (error || res.statusCode !== 200) {
              throw '更新版本号失败，请联系管理员';
            }
            const json = JSON.parse(body);
            const { version, description } = json;
            const localVersion = localpackage.version // 当前版本
            console.log('版本号不一致')
            if (version != localVersion) {
             // mainWindow.webContents.send('updating', '更新中') //主线程给渲染线程
              // 提示是否更新
              showUpdate(description)
           
            } else {
             
            }
          } catch (err) {
            reject(err);
          }
        })
    })
  }  
  /**
   * download
   */
   function downLoad()  {
    return new Promise((resolve, reject) => {
      
      
      percentPost(url, 'www.tt.com','/win32/app.zip');
      
    })
  }
 function showUpdate(desc) {
    dialog.showMessageBox({
      type:'info',
      title:'新版本提示',
      message:desc,
      buttons:['现在更新','暂不更新'],
      cancelId: 1
    },function(index){
        if(index==0){
          console.log('update')
          const notification = {
            title: '更新提醒：',
            body: '正在静默更新,你可以继续你的操作！'
            // silent:true
          }
          new Notification(notification).show()

            downLoad().then(() => {
                updateNow();
            })
        }else if(index==1){
          console.log('wait')
        }
    })
  }

  function updateNow(){
    dialog.showMessageBox({
      type:'info',
      title:'更新完成提示',
      message:"更新完成,是否重启",
      buttons:['马上体验新版本','稍后体验'],
      cancelId: 1
    },function(index){
        if(index==0){
          app.relaunch();  // 重启
          app.quit();
        }else if(index==1){
          console.log('')
        }
    })
  }

  function percentPost(url,host,path) {
    var req = http.request(
      {
        host,
        path,
        method: "HEAD",
      },
       (res)=> {
        //显示进度条
        if (res.statusCode == 200) {
          res.setEncoding(null);
          var str = progress({
            length: res.headers["content-length"],
            time: 5 /* ms */,
          });
          str.on("progress", function (progress) {

            var percentage = Math.round(progress.percentage).toFixed();
            if(percentage<100){
               //通知渲染线程同步
            // global.eventValue.returnValue = percentage
            // 通知渲染线程异步
            global.percentage = percentage
            
            global.eventValue.reply('show-percent',  percentage) // ELECTRON VERSION>5.0.13
            // global.eventValue.sender.send('show-percent',percentage)

            }
          });
          // request.get(url).pipe(str).pipe(fs.createWriteStream(`./di.zip`));
          let reader = request.get(url).pipe(str).pipe(fs.createWriteStream(`${baseUrl}/di.zip`));
          reader.on('close', () => {
            console.log('开始解压')
            const unzip = new AdmZip(`${baseUrl}/di.zip`);   //下载压缩更新包
            unzip.extractAllTo(`${baseUrl}`, /*overwrite*/true);    //解压替换本地文件
            console.log('覆盖成功');
            resolve()
          });
        } else {
          console.log('err')
        }
      }
    );
    req.on("error", (e) => {
      console.log('err')
    });
    req.end();
  }